import { Tag, Descriptions, Upload, Button, Image, message } from 'antd';
import { UploadOutlined, FileOutlined, FileImageOutlined, VideoCameraOutlined, AudioOutlined, FolderOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { CrudPage, ExportImport } from '@/components';
import type { SearchFormItem, CrudActionHandlers, CrudDataContext } from '@/components';
import { getFiles, uploadFile, deleteFile, batchDeleteFiles, downloadFile, type FileRecord } from './api';
import { Input, Select } from 'antd';

const { Option } = Select;

export default function FileManagementPage() {
  // 文件分类图标映射
  const categoryIcons = {
    document: <FileOutlined style={{ fontSize: 24, color: '#1890ff' }} />,
    image: <FileImageOutlined style={{ fontSize: 24, color: '#52c41a' }} />,
    video: <VideoCameraOutlined style={{ fontSize: 24, color: '#ff4d4f' }} />,
    audio: <AudioOutlined style={{ fontSize: 24, color: '#faad14' }} />,
    other: <FolderOutlined style={{ fontSize: 24, color: '#8c8c8c' }} />,
  };

  // 文件分类名称映射
  const categoryNames = {
    document: '文档',
    image: '图片',
    video: '视频',
    audio: '音频',
    other: '其他',
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  // 搜索配置
  const searchItems: SearchFormItem[] = [
    {
      name: 'originalName',
      label: '文件名',
      component: <Input placeholder="请输入文件名" allowClear />,
      col: 6,
    },
    {
      name: 'category',
      label: '文件分类',
      component: (
        <Select placeholder="请选择分类" allowClear>
          <Option value="document">文档</Option>
          <Option value="image">图片</Option>
          <Option value="video">视频</Option>
          <Option value="audio">音频</Option>
          <Option value="other">其他</Option>
        </Select>
      ),
      col: 6,
    },
  ];

  // 表格列配置
  const columns: ColumnsType<FileRecord> = [
    {
      title: '文件',
      dataIndex: 'originalName',
      key: 'originalName',
      width: 300,
      render: (name: string, record: FileRecord) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {record.category === 'image' && record.url ? (
            <Image
              src={record.url}
              alt={name}
              width={40}
              height={40}
              style={{ objectFit: 'cover', borderRadius: 4 }}
              preview={{
                src: record.url,
              }}
            />
          ) : (
            categoryIcons[record.category]
          )}
          <div style={{ flex: 1, overflow: 'hidden' }}>
            <div style={{ fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {name}
            </div>
            <div style={{ fontSize: 12, color: '#999' }}>{record.mimeType}</div>
          </div>
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category: keyof typeof categoryNames) => (
        <Tag color={category === 'document' ? 'blue' : category === 'image' ? 'green' : category === 'video' ? 'red' : category === 'audio' ? 'orange' : 'default'}>
          {categoryNames[category]}
        </Tag>
      ),
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      width: 100,
      render: (size: number) => formatFileSize(size),
    },
    {
      title: '上传人',
      dataIndex: ['user', 'firstName'],
      key: 'user',
      width: 120,
      render: (_: any, record: FileRecord) => {
        const user = record.user;
        if (!user) return '-';
        const fullName = `${user.firstName || ''} ${user.lastName || ''}`.trim();
        return fullName || user.email;
      },
    },
    {
      title: '上传时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  // 详情内容渲染
  const renderDetailContent = (record: FileRecord) => (
    <div>
      {record.category === 'image' && record.url && (
        <div style={{ marginBottom: 24, textAlign: 'center' }}>
          <Image
            src={record.url}
            alt={record.originalName}
            style={{ maxWidth: '100%', maxHeight: 400, borderRadius: 8 }}
          />
        </div>
      )}
      
      <Descriptions column={1} bordered>
        <Descriptions.Item label="文件名">{record.originalName}</Descriptions.Item>
        <Descriptions.Item label="文件类型">{record.mimeType}</Descriptions.Item>
        <Descriptions.Item label="文件大小">{formatFileSize(record.size)}</Descriptions.Item>
        <Descriptions.Item label="分类">
          <Tag color={record.category === 'document' ? 'blue' : record.category === 'image' ? 'green' : record.category === 'video' ? 'red' : record.category === 'audio' ? 'orange' : 'default'}>
            {categoryNames[record.category]}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="存储类型">
          {record.storageType === 'local' ? '本地存储' : record.storageType === 'oss' ? '阿里云OSS' : 'AWS S3'}
        </Descriptions.Item>
        <Descriptions.Item label="上传人">
          {record.user?.firstName || record.user?.lastName
            ? `${record.user?.firstName || ''} ${record.user?.lastName || ''}`.trim()
            : record.user?.email || '-'}
        </Descriptions.Item>
        <Descriptions.Item label="上传时间">
          {dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss')}
        </Descriptions.Item>
        {record.url && (
          <Descriptions.Item label="访问URL">
            <a href={record.url} target="_blank" rel="noopener noreferrer">
              {record.url}
            </a>
          </Descriptions.Item>
        )}
        {record.description && (
          <Descriptions.Item label="描述">{record.description}</Descriptions.Item>
        )}
      </Descriptions>

      <div style={{ marginTop: 16, textAlign: 'center' }}>
        <Button
          type="primary"
          onClick={() => downloadFile(record.id, record.originalName)}
        >
          下载文件
        </Button>
      </div>
    </div>
  );

  // 自定义头部操作 - 添加上传按钮
  const renderHeaderExtra = (handlers: CrudActionHandlers<FileRecord>, context: CrudDataContext<FileRecord>) => (
    <Upload
      showUploadList={false}
      beforeUpload={async (file) => {
        // 检查文件大小（30MB限制）
        const maxSize = 30 * 1024 * 1024; // 30MB
        if (file.size > maxSize) {
          message.error('文件大小不能超过30MB');
          return false;
        }

        try {
          const response = await uploadFile(file);
          if (response.data.success) {
            message.success('文件上传成功');
            handlers.onRefresh();
          }
        } catch (error: any) {
          console.error('上传失败:', error);
          message.error(error.response?.data?.message || '文件上传失败');
        }
        return false;
      }}
      multiple
    >
      <Button type="primary" icon={<UploadOutlined />}>
        上传文件
      </Button>
    </Upload>
  );

  // 自定义操作列 - 添加下载按钮
  const renderExtraActions = (record: FileRecord) => (
    <Button
      type="link"
      size="small"
      onClick={() => downloadFile(record.id, record.originalName)}
    >
      下载
    </Button>
  );

  return (
    <CrudPage<FileRecord>
      title="文件管理"
      fetchApi={getFiles}
      deleteApi={deleteFile}
      batchDeleteApi={batchDeleteFiles}
      columns={columns}
      searchItems={searchItems}
      scroll={{ x: 1200 }}
      showCreateButton={false}
      showEditButton={false}
      showViewButton={true}
      viewButtonText="详情"
      showDeleteButton={true}
      enableBatchDelete={true}
      batchDeleteButtonText="批量删除"
      detailDrawerTitle="文件详情"
      detailDrawerWidth={600}
      renderDetailContent={renderDetailContent}
      renderHeaderExtra={renderHeaderExtra}
      renderExtraActions={renderExtraActions}
      exportConfig={{
        filename: 'files',
        sheetName: '文件列表',
        columns: [
          { header: '文件名', key: 'originalName', width: 30 },
          { header: '文件类型', key: 'mimeType', width: 20 },
          { header: '文件大小(字节)', key: 'size', width: 15 },
          { header: '分类', key: 'category', width: 10 },
          { header: '存储类型', key: 'storageType', width: 10 },
          { header: '上传时间', key: 'createdAt', width: 20 },
        ],
      }}
      permissions={{
        create: false,
        update: false,
        delete: true,
      }}
      deleteConfirmTitle={(record) => `确定要删除文件"${record.originalName}"吗？`}
    />
  );
}

